package com.java2018.springmvc.book.service;

import com.java2018.springmvc.author.dao.AuthorMapper;
import com.java2018.springmvc.author.model.Author;
import com.java2018.springmvc.author.service.AuthorService;
import com.java2018.springmvc.book.dao.BookMapper;
import com.java2018.springmvc.book.model.Book;
import com.java2018.springmvc.utils.entity.Anonymous;
import com.java2018.springmvc.utils.entity.JsonResponse;
import com.java2018.springmvc.utils.uuid.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private AuthorService authorService;
    private boolean isSuccess = true;

    @Override
    public List<Book> getAll() {
        return bookMapper.getAll();
    }

    @Override
    @Transactional
    public JsonResponse add(Book book) throws Exception {
        JsonResponse jsonResponse = new JsonResponse();
        if(book.getAuthor()!=null){
            book.setId(UUIDUtil.getUUID());
            if(StringUtils.isNotBlank(book.getAuthor().getId())){
                // TODO: 查询数据库是否有该作者id，有则添加书，无则返回
                Author author = authorService.getOne(book.getAuthor());
                if(author!=null){
                    int bookCount = bookMapper.add(book);
                    if(bookCount==1){
                        this.isSuccess = true;
                    }
                }
            }
            if(StringUtils.isBlank(book.getAuthor().getId())&& StringUtils.isNotBlank(book.getAuthor().getChName())){
                //TODO: 如果作者id为空并且作者名不为空，则进行添加作者 再添加书
                int authorCount = authorService.add(book.getAuthor());
                if(authorCount==1){
                    int bookCount = bookMapper.add(book);
                    if(bookCount==1){
                        this.isSuccess = true;
                    }
                }else{
                    jsonResponse.setMsg("插入失败");
                }
            }
            if(StringUtils.isBlank(book.getAuthor().getId())&&StringUtils.isBlank(book.getAuthor().getChName())){
                //TODO: 如果作者id和作者名都为空，则添加无名作者
                book.getAuthor().setId(Anonymous.ANONYMOUS_AUTHOR_ID);
                int bookCount = bookMapper.add(book);
                if(bookCount==1){
                    this.isSuccess = true;
                }
            }

        }else{

        }
        if(isSuccess){
            jsonResponse.setMsg("插入成功");
            jsonResponse.setError(false);
        }

        return jsonResponse;
    }


}
